//
//  MYOAuthController.m
//  MYChatting
//
//  Created by mac on 16/7/30.
//  Copyright © 2016年 lhf. All rights reserved.
//

#import "MYOAuthController.h"
#import "SVProgressHUD.h"
#import "MYNetworkingTool.h"
#import "UserInfo.h"

@interface MYOAuthController ()<UIWebViewDelegate>

@property (nonatomic,weak) UIWebView *webView;

//@property (nonatomic,strong) UserInfo *userInfo;

@end

@implementation MYOAuthController

//注意：一般更换控制器的view都是在方法loadView中进行的
- (void)loadView{
    UIWebView *webView = [[UIWebView alloc] init];
    self.view = webView;
    self.webView = webView;
    webView.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    //由于oauth授权页面是web网页，因此创建webview
   
    //redirect_uri=http://www.tozlc.com"即是应用中的高级信息的授权回调页
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=783300818&redirect_uri=http://www.tozlc.com"]]];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancle)];
    
    //添加自动填充按钮
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(defautInfo)];
}

//- (void)defautInfo{
//    NSString * jsString = @"document.getElementById[@"userId"].value ==
//    @"18801021137",document.getElementById('passwd').value = '1735845520G'";
//    
//    [self.webView stringByEvaluatingJavaScriptFromString(jsString)];
//}

- (void)cancle{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark UIWebViewDelegate的代理方法

- (void)webViewDidStartLoad:(nonnull UIWebView *)webView{
    [SVProgressHUD show];
   
}

- (void)webViewDidFinishLoad:(nonnull UIWebView *)webView{
    [SVProgressHUD dismiss];
}

/**
 最开始方法中的代码：（目的是查看返回的urlString)
  NSString *urlString = request.URL.absoluteString;
  NSLog(@"%@",urlString);
  return true;
    返回的urlString：我们只需要带有code的那一个，因此需要进行筛选
 2016-07-30 11:02:28.023 MYChatting[10666:99437] https://api.weibo.com/oauth2/authorize?client_id=783300818&redirect_uri=http://www.tozlc.com
 2016-07-30 11:02:44.471 MYChatting[10666:99437] https://api.weibo.com/oauth2/authorize
 2016-07-30 11:03:01.169 MYChatting[10666:99437] https://api.weibo.com/oauth2/authorize#
 2016-07-30 11:03:01.207 MYChatting[10666:99437] https://api.weibo.com/oauth2/authorize
 2016-07-30 11:03:01.288 MYChatting[10666:99437] http://www.tozlc.com/?code=20d2190585f7cb6607362252e831ea4c
 2016-07-30 11:03:01.340 MYChatting[10666:99437] http://www.tozlc.com/wap/index.php

 */

- (BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlString = request.URL.absoluteString;
    
    if ([urlString hasPrefix:@"https://api.weibo.com"]) {
        return true;
    }
    
    if ([urlString hasPrefix:@"http://www.baidu.com"]) {
        return false;
    }
    
    if ([urlString containsString:@"http://www.tozlc.com/?code="]) {
        NSString *query = request.URL.query;
        NSString *codeStr = @"code=";
        //获得用户授权的code码 用此来获得accesstoken
        NSString *code = [query substringFromIndex:[codeStr rangeOfComposedCharacterSequenceAtIndex:4].location + 1];
//        NSLog(@"%@",urlString);
//        NSLog(@"%@",code);
       //获得accessToken码
        [self loadAccessTokenWithCode:code];
    }
   
    return true;
}


- (void)loadAccessTokenWithCode:(NSString *)code{
    NSDictionary *parameterDict = @{@"client_id":client_id,@"client_secret":client_secret,@"grant_type":@"authorization_code",@"code":code,@"redirect_uri":redirect_uri};
    
    [[MYNetworkingTool sharedMYNetworkingTool] POST:@"https://api.weibo.com/oauth2/access_token" parameters:parameterDict progress:^(NSProgress * _Nonnull uploadProgress) {
       // NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = responseObject;
        
        UserInfo *userInfo = [UserInfo userInfoWithDict:responseDict];
        
//        NSLog(@"%@",responseObject);
//        NSLog(@"%@",responseDict);
//        NSLog(@"%@",responseDict[@"access_token"]);
//        NSString *access_token = responseDict[@"access_token"];
//        NSString *uid = responseDict[@"uid"];
        
        // 获得用户的信息下
//      [self loadUserInfoWithAccessToken:access_token andUid:uid];
       // [self loadUserInfoWithAccessToken:userInfo.access_token andUid:userInfo.uid];
        [self loadUserInfoWithUserInfo:userInfo];
        
//        //发布通知
//        [[NSNotificationCenter defaultCenter] postNotificationName:MYSwitchRootVCNotification object:@"welcome"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

//- (void)loadUserInfoWithAccessToken:(NSString *)accessToken andUid:(NSString *)uid{
- (void)loadUserInfoWithUserInfo:(UserInfo *)userInfo{
    NSDictionary *parameterDict = @{@"access_token":userInfo.access_token,@"uid":userInfo.uid};
  //  NSDictionary *parameterDict = @{@"access_token":accessToken,@"uid":uid};
    [[MYNetworkingTool sharedMYNetworkingTool] GET:@"https://api.weibo.com/2/users/show.json" parameters:parameterDict progress:^(NSProgress * _Nonnull downloadProgress) {
      //  NSLog(@"%@",downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resDict = responseObject;
        
       // UserInfo *userInfo = [[UserInfo alloc] init];
        userInfo.name = resDict[@"name"];
        userInfo.avatar_large = resDict[@"avatar_large"];
        
        
        //保存客户的信息
        [userInfo saveUserInfo];
//        NSLog(@"%@",userInfo.name);
//        NSLog(@"%@",userInfo.avatar_large);
        
        //测试归档数据是否成功用的
       // [self loadddddd];
        
        //发布通知
        [[NSNotificationCenter defaultCenter] postNotificationName:MYSwitchRootVCNotification object:@"welcome"];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}



//- (void)loadddddd{
//    UserInfo *userInfo = [[[UserInfo alloc] init] loadUserInfo];
//    NSLog(@"name---%@,ave-----%@,large------%@,token------%@,uid------%@",userInfo.name,userInfo.avatar_large,userInfo.avatar_large,userInfo.access_token,userInfo.uid);
//}

@end
